package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    private StringRedisTemplate redisTemplate;

    //锁相关字段
    private String name;    //业务对应的锁的名称
    private static final String KEY_PREFIX = "lock:";   //统一前缀
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-"; //线程ID的前缀，防止线程重复

    public SimpleRedisLock(StringRedisTemplate redisTemplate, String name) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        String key = KEY_PREFIX + name;     //锁的名称

        String threadId = ID_PREFIX + Thread.currentThread().getId(); //线程id，作为值存入，表示当前获取锁的线程

        //尝试获取锁
        Boolean success = redisTemplate.opsForValue()
                .setIfAbsent(key, threadId, timeoutSec, TimeUnit.SECONDS);

        //返回结果
        return BooleanUtil.isTrue(success); //自动拆箱可能存在空指针风险！
    }

    //提前加载lua脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    @Override
    public void unLock() {
        String key = KEY_PREFIX + name;     //锁的名称

        String threadId = ID_PREFIX + Thread.currentThread().getId(); //线程id，作为值存入，表示当前获取锁的线程

        //调用lua脚本
        redisTemplate.execute(
                UNLOCK_SCRIPT,  //要执行的脚本对象
                Collections.singletonList(key),     //传给脚本中redis对象的key
                threadId    //传给脚本中用于与redis值进行比较的内容
        );
    }

    /*@Override
    public void unLock() {
        String key = KEY_PREFIX + name;
        String threadId = ID_PREFIX + Thread.currentThread().getId();

        //获取线程标识
        String value = redisTemplate.opsForValue().get(key);

        //判断是否为同一线程持有
        if (value.equals(threadId))
            redisTemplate.delete(KEY_PREFIX + name);
        else
            System.out.println("不同线程持有的锁，无法删除！");
    }*/
}
